<template>
    <div>
        <h4 v-for="good in goods" :key="good.id">{{ good.goods_desc }}</h4>
        <button @click="getGoods">获取数据</button>
        <button @click="registerUser">注册</button>
        <button @click="loginUser">登录</button>
        <button @click="A">Promise.all</button>
        <button @click="B">Promise.race</button>
        <button @click="C">Promise.allSettled</button>
        <h4 v-if="users.length">用户注册：{{ users[0].username }}</h4>
        <h4 v-if="loginUsers.length">用户登录：{{ loginUsers[0].username }}</h4>
    </div>
</template>

<script setup>
    import axios from 'axios';
    import request from '../../utils/request';
    import { ref, reactive, onMounted} from 'vue';


    const users = ref([]);
    const loginUsers = ref([]);
    const goods = reactive([]);


    function getGoods() {
        let api = '/goods/getGoodsPage?goods_category=1&currentPage=1&pageSize=3'
        // const xhr = new XMLHttpRequest();
        // xhr.open('GET', api);
        // xhr.send();
        // xhr.onreadystatechange = () => {
        //     if (xhr.readyState === 4) {
        //         if (xhr.status === 200) {
        //             const { code, data:res, message } = JSON.parse(xhr.responseText);
        //             if (code === 200) {
        //                 // goods.value = res
        //                 goods.splice(0, goods.length, ...res)
        //             }
        //             else {
        //                 console.log(message)
        //             }
        //         } 
        //     }
        // }


        // fetch(api)
        //    .then(response => response.json())
        //    .then(data => {
        //         const { code, data:res, message } = data;
        //         if (code === 200) {
        //             goods.splice(0, goods.length, ...res)
        //         }
        //         else {
        //             console.log(message)
        //         }
        //     })
        //    .catch(error => console.log(error))


        // axios.get(api)
        //     .then(response => {
        //         console.log(response.data)
        //         const { code, data:res, message } = response.data;
        //         if (code === 200) {
        //             goods.splice(0, goods.length, ...res)
        //         }
        //         else {
        //             console.log(message)
        //         }
        //     })
        //     .catch(error => console.error(error));

        
        request.get(api)
            .then(response => {
                const { code, data:res, message } = response
                if (code === 200) {
                    goods.splice(0, goods.length, ...res)
                }
                else {
                    console.log(message)
                }
            })
    }

    function registerUser() {
        const xhr = new XMLHttpRequest();
        let api = '/api/user/register'
        xhr.open('POST', api);
        xhr.setRequestHeader('Content-Type', 'application/json');
        const userData = {
            id: 20030404,
            username: 'zm4',
            password: '123456'
        }
        xhr.send(JSON.stringify(userData));
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const { code, data:res, message } = JSON.parse(xhr.responseText);
                    if (code === 200) {
                        login.value = [res]
                        console.log(login.value)
                    }
                    else {
                        console.log(message)
                    }
                } 
            }
        }
    }

    function loginUser() {
        let api = '/api/user/login'
    //     fetch(api, {
    //         method: 'POST',
    //         headers: {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify({
    //             username: 'zm4',
    //             password: '123456'
    //         })
    //     })
    //    .then(response => response.json())
    //    .then(data => {
    //         const { code, data:res, message } = data;
    //         if (code === 200) {
    //             loginUsers.value = [res]
    //             console.log(loginUsers.value)
    //         }
    //         else {
    //             console.log(message)
    //         }
    //     })
    //    .catch(error => console.error(error))


        axios.post(api, {
            username: 'zm4',
            password: '123456'
        })
            .then(response => {
                console.log(response.data)
                const { code, data:res, message } = response.data;
                if (code === 200) {
                    loginUsers.value = [res]
                    console.log(loginUsers.value)
                }
                else {
                    console.log(message)
                }
            })
            .catch(error => console.error(error));

    }

    const promist = new Promise((resolve, reject) => {
        let num = Math.random()
        if (num > 0.5) {
            resolve(['成功', num])
        } else {
            reject(['失败', num])
        }
    })
    promist.then(res => {
        console.log(res[0], res[1])
    }).catch(err => {
        console.log(err[0], err[1])
    })


    function A() {  
        Promise.all([
            request.get('/users'),
            request.get('/todos'),
        ]).then(responses => {
            console.log('所有请求完成');
        }).catch(error => {
            console.log('有请求失败', error);
        });
    }
    
    function B() {  
        Promise.race([
            request.get('/users'),
            request.get('/todos'),
        ]).then(result => {
            console.log('最快的请求结果:', result);
        }).catch(error => {
            console.log('最快的失败请求:', error);
        });
    }

    function C() {  
        Promise.allSettled([
            request.get('/users'),
            request.get('/todos'),
        ]).then(results => {
            results.forEach(result => {
                if (result.status === 'fulfilled') {
                    console.log('成功:', result.value);
                } else {
                    console.log('失败:', result.reason);
                }
            });
        });
    }
</script>
